//
//  SCTextField.swift
//  iPhone
//
//  Created by Toj on 8/28/22.
//

import UIKit

enum SCTextFieldStyle {
    case titleLeft
    case titleTop
}

class SCTextField: UIView {
    
    var style: SCTextFieldStyle = .titleTop
    
    var lineHeight: CGFloat = 1
    var charFormatType: String.SPFormatterType = .threeFourFour
    var maxCharCount = 0 { didSet {
        guard maxCharCount > 0 else {
            maxCharLabel.isHidden = true
            return
        }
        maxCharLabel.isHidden = false
        maxCharLabel.text = "0/\(maxCharCount)"
    } }
    
    var textSeparator = " "
    
    var text: String {
        get {
            if textSeparator.isEmpty {
                return textField.text ?? ""
            }
            
            return textField.text?.replacingOccurrences(of: textSeparator, with: "") ?? ""
        }
        
        set {
            textField.text = newValue
        }
    }
    
    var rightView: UIView? = nil { didSet {
        guard let view = rightView else { return }
        
        addSubview(view)
    } }
    
    private(set) lazy var titleLabel: UILabel = {
        let view = UILabel()
        return view
    }()
    
    private(set) lazy var textField: UITextField = {
        let view = UITextField()
        view.delegate = self
        view.backgroundColor = UIColor.white
        view.autocorrectionType = .no
        view.autocapitalizationType = .none
        view.addTarget(self, action: #selector(textFieldEditingChange(with:)), for: .editingChanged)
        return view
    }()
    
    private(set) lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = "#DDDDDD".to_color
        return view
    }()
    
    private(set) lazy var maxCharLabel: UILabel = {
        let view = UILabel()
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupMakeAddSubviews()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setupMakeLayoutSubviews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private let defaultFont = UIFont.systemFont(ofSize: 12)
}


extension SCTextField: UITextFieldDelegate {
    
    @objc private func textFieldEditingChange(with sinder: UITextField) {
        
        guard let string = sinder.text?.replacingOccurrences(of: textSeparator, with: "") else {
            maxCharLabel.text = "0/\(maxCharCount)"
            return
        }
        // print("-->toj:count: \(string.count)")
        
        let count = string.count
        maxCharLabel.text = "\(count)/\(maxCharCount)"
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 不是数字直接过滤
        let lenth = string.lengthOfBytes(using: .utf8)
        for lindex in 0..<lenth {
            let char = (string as NSString).character(at: lindex)
            if char < 48 || char > 57 {
                return false
            }
        }
        
        // 输入字符 首先拼接出输入之后的字符串
        let text = (textField.text ?? "") as NSString
        var textString = text.replacingCharacters(in: range, with: string)
        
        // print("-->toj: range: \(range)")
        var offset = range.location
        let length = range.length
        // 代表删除
        if string.isEmpty {
            if length == 1 {
                offset -= length
            }
        }
        else {
            offset += string.count
        }
        
        
        var validString = textString.replacingOccurrences(of: textSeparator, with: "")
        
        // print("-->toj: validString: \(validString)")
        
        textField.text = validString
        
        if validString.count > maxCharCount {
            let startIndex = validString.startIndex
            let middleIndex = validString.index(startIndex, offsetBy: maxCharCount)
            let range = middleIndex..<validString.endIndex
            validString.removeSubrange(range)
        }
        
        textString = validString.cm_numberFormat(format: charFormatType, separator: textSeparator)
        textField.text = textString
        
        guard let newPosition = textField.position(from: textField.beginningOfDocument, offset: offset)
        else { return false }
        
        textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
        
        return false
    }
    
    private func charCount(_ string: String, char: CChar) -> Int {
        let ASCII = char.to_ASCII ?? ""
       let str = string.replacingOccurrences(of: ASCII, with: "")
        return string.count - str.count
    }
}


// MARK: - 初始化
extension SCTextField {
    
    private func setupMakeAddSubviews() {
        
        addSubview(titleLabel)
        addSubview(textField)
        addSubview(lineView)
        addSubview(maxCharLabel)
    }
    
    private func setupMakeLayoutSubviews() {
        var height = CGFloat.zero
        if maxCharCount > 0 {
            height = "9/9".cm_stringOneLineHeight(font: maxCharLabel.font)
            maxCharLabel.snp.makeConstraints { make in
                make.bottom.right.equalTo(self)
                make.height.equalTo(height)
            }
        }
        let bottom = height > 0 ? (height + 8) : 0
        lineView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.height.equalTo(lineHeight)
            make.bottom.equalTo(-bottom)
        }
        
        if style == .titleTop {
            titleLabel.snp.makeConstraints { (make) in
                make.top.left.right.equalTo(self)
            }
            
            var size = CGSize.zero
            if let view = rightView {
                size = view.frame.size
            }
            let right = size.width + 5 // margin = 5
            let font = textField.font ?? defaultFont
            height = "9".cm_stringOneLineHeight(font: font)
            textField.snp.makeConstraints { (make) in
                make.left.equalTo(self)
                make.top.equalTo(titleLabel.snp.bottom).offset(12)
                make.height.equalTo(height)
                make.right.equalTo(-right)
            }
            
            rightView?.snp.makeConstraints { make in
                make.right.equalTo(self)
                make.centerY.equalTo(textField)
                make.height.equalTo(size.height)
                make.width.equalTo(size.width)
            }
            return
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.top.equalTo(self)
            make.bottom.equalTo(lineView.snp.top)
        }
        
        var size = CGSize.zero
        if let view = rightView {
            size = view.frame.size
        }
        let right = size.width + 5 // margin = 5
        let font = textField.font ?? defaultFont
        height = "9".cm_stringOneLineHeight(font: font)
        textField.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel.snp.right).offset(5)
            make.centerY.equalTo(titleLabel)
            make.height.equalTo(height)
            make.right.equalTo(-right)
        }
        
        rightView?.snp.makeConstraints { make in
            make.right.equalTo(self)
            make.centerY.equalTo(textField)
            make.height.equalTo(size.height)
            make.width.equalTo(size.width)
        }
    }
}
